package com.farm.utils_all;

import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import net.sf.json.JSONObject;

public class WXUtil {

	public static String createCode() {
		return "";
	}

	public static String getToken() {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constants.APPID
				+ "&secret=" + Constants.SecretKey;
		try {
			JSONObject jsonObject = AuthUtils.doGetJson(url);
			return jsonObject.get("access_token").toString();
		} catch (Exception e) {
			// TODO: handle exception
		}
	
		return "";
	}
	public static String decrypt(String encryptedData, String key, String iv) {
		// 被加密的数据
		byte[] dataByte = org.apache.shiro.codec.Base64.decode(encryptedData);
		// 加密秘钥
		byte[] keyByte = org.apache.shiro.codec.Base64.decode(key);
		// 偏移量
		byte[] ivByte = org.apache.shiro.codec.Base64.decode(iv);
		try {
			// 如果密钥不足16位，那么就补足.
			int base = 16;
			if (keyByte.length % base != 0) {
				int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
				byte[] temp = new byte[groups * base];
				Arrays.fill(temp, (byte) 0);
				System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
				keyByte = temp;
			}
			// 初始化
			Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
			AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
			parameters.init(new IvParameterSpec(ivByte));
			cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
			byte[] resultByte = cipher.doFinal(dataByte);
			if (null != resultByte && resultByte.length > 0) {
				String result = new String(resultByte, "UTF-8");
				/* return JSONObject.parseObject(result); */
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}
